<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" :model="findResult" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="findResult.sname" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="findResult.sex" placeholder="性别"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="findResult.address" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="findResult.cid" placeholder="所在班级">
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addStudent()">添加学生</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="StudentList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>>
        <el-table-column
            label="学号"
            align="center"
            prop="sid">
        </el-table-column>
        <el-table-column
            label="姓名"
            align="center"
            prop="sname">
        </el-table-column>
        <el-table-column
            label="性别"
            align="center"
            prop="sex">
        </el-table-column>
        <el-table-column
            label="地址"
            align="center"
            prop="address">
        </el-table-column>
        <el-table-column
            label="班级"
            align="center"
            prop="cname">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 导航 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <el-dialog :title="title" :visible.sync="dialogFormVisible"  >
      ${{product}}
      <el-form :model="student" :rules="rules" ref="ruleForm">
        <el-form-item label="姓名" prop = "sname" :label-width="formLabelWidth">
          <el-input v-model="student.sname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop = "sex" :label-width="formLabelWidth">
          <el-radio v-model="student.sex" label="男">男</el-radio>
          <el-radio v-model="student.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="地址" prop = "address" :label-width="formLabelWidth">
          <el-input v-model="student.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在班级" prop="cid" :label-width="formLabelWidth">
          <el-select v-model="student.cid" placeholder="请选择班级">
            <el-option :label="c.cname" :value="c.cid" v-for="c in classList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import studentApi from "@/api/student";
import classApi from "@/api/class"

export default {
  data() {
    return {
      StudentList: [], // 存储学生数据
      page: 1, // 当前页 默认1
      pageSize: 10, // 默认每页显示10条
      total: 0, // 总记录数 默认0
      findResult: {}, //查询条件对象，初始化为空对象
      classList: [],// 存储班级列表
      dialogFormVisible:false,
      formLabelWidth:'100px',
      student:{},
      multipleSelection:[],
      title:"添加学生",
      rules: {
        // 1. 校验学生姓名
        sname: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在2到20个字符之间', trigger: 'blur' }
        ],

        // 2. 校验学生性别
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        // 4. 校验学生住址
        address: [
          { required: true, message: '请输入学生住址', trigger: 'blur' },
          { min: 2, max: 100, message: '住址长度应在5到100个字符之间', trigger: 'blur' }
        ],
        // 5. 校验学生班级
        cname: [
          { required: true, message: '请选择学生班级', trigger: 'change' }
        ]
      }

    };
  },
  created() {
    // 页面创建时默认加载数据
    // this.findByPage(this.page, this.pageSize);
    this.onSubmit();
    this.findClass();
  },
  methods: {
    async findStudents() {
      const { data: res } = await studentApi.findAllProducts();
      if (res.code === 200) {
        this.StudentList = res.data.list;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 点击查询按钮触发查询，包括分页和条件
    async onSubmit() {
      const { data: res } = await studentApi.searchProduct(this.page, this.pageSize, this.findResult);
      console.log(res)
      if (res.code === 200) {
        this.StudentList = res.data.pageResult.rows; // 获取学生数据
        this.total = res.data.pageResult.total; // 获取总条数
      }
    },
    // 分页查询
    async findByPage(page, pageSize, findResult = {}) {
      const { data: res } = await studentApi.findByPage(page, pageSize, findResult);
      if (res.code === 200) {
        this.StudentList = res.data.pageResult.rows; // 获取学生数据
        this.total = res.data.pageResult.total; // 获取总条数
      }
    },
    // 查找班级
    async findClass() {
      const { data: res } = await classApi.findAllClass();
      if (res.code === 200) {
        this.classList = res.data.list; // 获取班级数据，确保有默认值
      }
    },
    addStudent(){
      this.student = {};
      this.dialogFormVisible = true ;
    },
    // 改变每页显示的条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.findByPage(this.page, this.pageSize, this.findResult); // 重新加载数据
    },
    submitForm() {
      this.$refs.ruleForm.validate(async valid => {
        let url = "/student/addStudent"
        let method = "post"
        if(this.student.sid){
          url = "/student/updateStudent"
          method = "put"
        }
        if (valid) {
          console.log("1111")
          const {data:res} = await studentApi.saveStudent(url,method,this.student)
          console.log("res:",res)
          console.log("2222")
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {
                this.dialogFormVisible = false
                this.onSubmit()
              }
            })
          }else{
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.page = val; // 改变当前页
      this.findByPage(this.page, this.pageSize, this.findResult); // 重新加载数据
    },

    // 编辑操作
    handleEdit(index, row) {
      console.log(index, row);
      this.title = '修改学生'
      this.student = row
      this.dialogFormVisible = true
    },

    // 删除操作
    handleDelete(index, row) {
      this.pids = row ? [row.sid] : this.multipleSelection.map(m => m.sid);
      this.$confirm(`是否真的要删除学号为${this.pids.join(', ')}的学生吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        studentApi.deleteStudent(this.pids)
            .then(({ data: res }) => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: this.onSubmit // 删除后重新加载数据
                });
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                });
              }
            })
            .catch((error) => {
              console.error("删除学生失败:", error);
              this.$message({
                type: 'error',
                message: '删除学生失败，请稍后再试！'
              });
            });
      }).catch(() => {
        // 用户取消删除
        console.log("删除操作已取消");
      });
    }

  }
};

</script>

<style>

</style>
